package cn.jilian.sys.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.jilian.common.dto.PageInfo;
import cn.jilian.common.dto.PageResult;
import cn.jilian.common.dto.SortInfo;
import cn.jilian.common.util.MD5Util;
import cn.jilian.dao.AuthDAO;
import cn.jilian.dao.LinkDAO;
import cn.jilian.dao.MaceDAO;
import cn.jilian.dao.UserDAO;
import cn.jilian.entity.Auth;
import cn.jilian.entity.User;
import cn.jilian.sys.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private AuthDAO authDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private MaceDAO maceDAO;
	
	@Autowired
	private LinkDAO linkDAO;
	
	
	@Override
	public Auth findByUsername(String username) {
		
		return authDAO.findByUsername(username);
	}

	@Override
	public long verify(String username, String password) {
		Auth auth=this.findByUsername(username);
		if(auth==null)return -1;
		String data=MD5Util.GetMD5Code(password+auth.getSalt());
		if(StringUtils.equals(data, auth.getPass())) {
			return auth.getFid();
		}
		return -2;
	}

	@Override
	public User findById(long id) {
		
		return userDAO.findOne(id);
	}

	@Override
	public long addUser(User user) {
		String username=user.getUsername();
		User u=userDAO.findByUsername(username);
		if(u!=null) {
			return -1;
		}
		user= userDAO.save(user);
		return user.getId();
	}

	@Override
	public long addAuth(Auth auth) {
		Integer seq=authDAO.getMaxSeq(auth.getFid(), auth.getRank());
		seq=seq==null?1:seq+1;
		auth.setSeq(seq);
		auth=authDAO.save(auth);
		if(auth!=null) {
			return auth.getId();
		}
		return 0;
	}

	@Override
	public void deleteUser(long id) {
		userDAO.delete(id);
		authDAO.deleteByFid(id);
		maceDAO.deleteByUid(id);
		linkDAO.deleteBySource(id);
	}

	@Override
	public PageResult<User> queryByUnid(PageInfo pageInfo, SortInfo sortInfo, Long unid) {
		int pageIndex=((Number)(pageInfo.getStart()/pageInfo.getLimit())).intValue();
		
		PageRequest page=new PageRequest(pageIndex,pageInfo.getLimit(),
				StringUtils.equalsIgnoreCase(sortInfo.getDirect(), "ASC")?Direction.ASC:Direction.DESC,sortInfo.getField());
		Page<User> result=userDAO.findByUnitId(unid, page);
		pageInfo.setTotal(result.getTotalElements());
		pageInfo.setCache(result.getNumber());
		PageResult<User> rs=new PageResult<>(pageInfo,result.getContent());
		return rs;
	}

}
